package org.university.service;

import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.university.entity.User;
import org.university.repository.UserRepository;

/**
 * 自定义UserDetailsService，避免使用默认的InMemoryUserDetailsManager
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final static Logger LOGGER = LoggerFactory.getLogger(CustomUserDetailsService.class);

    @Resource
    private UserRepository userRepository; // 假设你有用户Mapper用于查询数据库

    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
//        LOGGER.debug("尝试加载用户: {}", userId);

        try {
            User user = userRepository.findByUserId(userId)
                    .orElseThrow(() -> {
                        LOGGER.warn("用户不存在: {}", userId);
                        return new UsernameNotFoundException("用户不存在: " + userId);
                    });

//            LOGGER.debug("找到用户: {} - {}", user.getUserId(), user.getUserName());

            // 转换为Spring Security的UserDetails
            return org.springframework.security.core.userdetails.User
                    .withUsername(user.getUserId())
                    .password(user.getPasswordEncrypted())
                    .roles(String.valueOf(user.getRole()))
                    .build();
        } catch (Exception e) {
            LOGGER.error("加载用户时发生错误: {}", userId, e);
            throw e;
        }
    }
}
